package com.szsh.bigdata.open.utils

import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import redis.clients.jedis.JedisPool

object RedisClient {
	private val redisHost: String = "***.**.***.***"
	private val redisPort: Int = 6379
	private val redisTimeOut: Int = 30000 // ms
	private val maxTotal = 300
	private val maxIdle = 100
	private val minIdle = 1
	
	@transient private var pool: JedisPool = _
	makePool(redisHost, redisPort, redisTimeOut, maxTotal, maxIdle, minIdle)
	
	def makePool(redisHost: String, redisPort: Int, redisTimeout: Int,
				 maxTotal: Int, maxIdle: Int, minIdle: Int): Unit = {
		makePool(redisHost, redisPort, redisTimeout, maxTotal, maxIdle, minIdle, testOnBorrow = true, testOnReturn = false, 10000)
	}
	
	def makePool(redisHost: String, redisPort: Int, redisTimeout: Int,
				 maxTotal: Int, maxIdle: Int, minIdle: Int, testOnBorrow: Boolean,
				 testOnReturn: Boolean, maxWaitMillis: Long): Unit = {
		if (pool == null) {
			val poolConfig = new GenericObjectPoolConfig()
			poolConfig.setMaxTotal(maxTotal)
			poolConfig.setMaxIdle(maxIdle)
			poolConfig.setMinIdle(minIdle)
			poolConfig.setTestOnBorrow(testOnBorrow)
			poolConfig.setTestOnReturn(testOnReturn)
			poolConfig.setMaxWaitMillis(maxWaitMillis)
			pool = new JedisPool(poolConfig, redisHost, redisPort, redisTimeout)
			
			val hook = new Thread {
				override def run(): Unit = pool.destroy()
			}
			sys.addShutdownHook(hook.start())
		}
	}
	
	def getPool: JedisPool = {
		assert(pool != null)
		pool
	}
	
	
	def main(args: Array[String]): Unit = {
		val jedis = getPool.getResource
		val value = jedis.set("name", "test")
		println(s"value is $value")
		jedis.close()
	}
}